import olap.xmla.xmla as xmla


class MyCube:
    def __init__(self, location, username, password, connect=None):
        self.location = location
        self.username = username
        self.password = password
        self.connect = connect
        self.get_connect()

    def get_connect(self):
        provider = xmla.XMLAProvider()
        defaultwsdl = xmla.defaultwsdl.replace('file://', '')
        self.connect = provider.connect(url=defaultwsdl, location=self.location, username=self.username,
                                        password=self.password)
        return self.connect

    def get_catalog(self, catalog_name=None):
        '''
        获取多维数据集库对象和名字, 并一字典形式{catalog_name: catalog}返回
        :param catalog_name: SSAS库名称，传参则获取单个，不传则获取连接下所有
        :return:
        '''
        if catalog_name:
            catalog = self.connect.getCatalog(catalog_name)
            catalog_name = catalog.CATALOG_NAME
            result = {catalog_name: catalog}
        else:
            catalogs = self.connect.getCatalogs()
            result = [{catalog.CATALOG_NAME: catalog} for catalog in catalogs]
        return result

    def get_cube(self, catalog, cube_name=None):
        '''
        获取多维数据集cube
        :param catalog: 必传参数，SSAS库
        :param cube_name: 传参则取单个cube,不传则取当前库所有cube
        :return:
        '''
        if cube_name:
            cube = catalog.getCube(cube_name)
            cube_name = cube.CUBE_NAME
            result = {cube_name: cube}
        else:
            cubes = catalog.getCubes()
            result = [{cube.CUBE_NAME: cube} for cube in cubes]
        return result

    def get_measure(self, cube):
        '''
        获取cube下量值
        :param cube: 多维数据集对象
        :return:
        '''
        measures = cube.getMeasures()
        result = [{measure.MEASURE_NAME: measure} for measure in measures]
        return result

    def get_dimension(self, cube):
        '''
        获取cube下维度
        :param cube: 多维数据集对象
        :return:
        '''
        dimensions = cube.getDimensions()
        result = [{dimension.DIMENSION_NAME: dimension} for dimension in dimensions if
                  dimension.DIMENSION_NAME != 'Measures']
        return result


if __name__ == '__main__':
    conn = MyCube(location='http://127.0.0.1:8888/msmdpump.dll', username='Win10-2020YKVZB\Administrator',
                  password='zjs')
    catalog = conn.get_catalog('YWC_SSAS')
    print(catalog)
    cube = conn.get_cube(catalog.get('YWC_SSAS'), '抗菌药物分析')
    print(cube)
    measures = conn.get_measure(cube.get('抗菌药物分析'))
    print(len(measures))
    dims = conn.get_dimension(cube.get('抗菌药物分析'))
    print(dims)
